package com.wmh.baseservice.skd.controller;

import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.PathUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.utils.upload.service.CosService;
import com.wmh.baseservice.user.enums.FileTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Api(tags = "公开接口")
@Validated
@RestController
    @RequestMapping(value = "public", produces = "text/plain;charset=utf-8")
@Slf4j
public class PublicController {
    @Resource
    private CosService cosService;

    /**
     * #0011 公共上传文件接口
     * @param fileType 文件类型
     * @param files 上传的文件
     * @return 返回上传的文件url地址
     * @throws IOException 文件IO异常
     */
    @ApiOperation("公共上传文件接口")
    @PostMapping("upload")
    public String uploadAvatar(@NotBlank(message = "未提交文件类型") String fileType, @NotNull(message = "未提交文件") List<MultipartFile> files) throws IOException {
        List<String> imgUrls = new ArrayList<>();
        // 获取文件类型
        FileTypeEnum type = FileTypeEnum.fromString(fileType);
        // 如果提交未知文件类型返回异常错误
        if(type == FileTypeEnum.UNKNOWN) {
            // 处理错误或返回错误信息
            return ReturnBody.error("请提交正确的文件类型!");
        }
        for (MultipartFile file : files) {
            // 获取原文件名并生成唯一文件名
            String uniqueFilename = CommUtil.generateUniqueFileName(Objects.requireNonNull(file.getOriginalFilename()));
            String suffix = uniqueFilename.substring(uniqueFilename.lastIndexOf("."));
            // 判断文件格式是否支持
            List<String> supportedFormats = Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".mp4", ".avi", ".mov");
            if (!supportedFormats.contains(suffix.trim().toLowerCase())) {
                return ReturnBody.error("文件格式不支持");
            }

            String upload = cosService.upload(file.getBytes(), type.getKey() + uniqueFilename);

            if ("error".equals(upload)) { return ReturnBody.error("图片上传失败!"); }

            String imgUrl = PathUtil.COS_DOMAIN + upload;
            imgUrls.add(imgUrl);
        }
        return ReturnBody.success(imgUrls);
    }
}
